package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowow.comment.domain.StrategyComment;
import cn.wolfcode.luowow.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowow.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService{

    @Autowired
    private IStrategyCommentRepository repository; //crud操作

    @Autowired
    private MongoTemplate template;  //高级查询

    @Override
    public void save(StrategyComment comment) {

        comment.setCreateTime(new Date());
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //需要查询评论列表并分页显示,而且目前有的api无法直接得到分页对象Page
        //只能通过之前的高级查询时候弄个pageResult,总结封装Page对象

        Query query = new Query();

        //查询条件
        if(qo.getDetailId() !=-1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }

        //第一个参数是当前页,因为是从0开始的,所以我们要-1,第二个是页面大小,第三个是排序,第四个是排序的列
       Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");

        //查询总数
        Long total = template.count(query,StrategyComment.class);

        if(total == null){
            return Page.empty();
        }

        //查询当前显示页数
        List<StrategyComment> list = template.find(query, StrategyComment.class);

        //返回 的是一个分页的,因为是一个接口的,所有我们要new一个实现类出来返回,分页内容还没有,先不要管
        return new PageImpl(list,pageable,total);

    }

    @Override
    public void commentThumbUp(String toid, Long userId) {
        //判断当前请求时点赞还是取消点赞
        Optional<StrategyComment> optional = repository.findById(toid);
        StrategyComment comment = optional.get();

        if(comment == null){
            return;
        }
        //用一个数组来接收
        List<Long> thumbuplist = comment.getThumbuplist();

        //判断是否点赞
        if(!thumbuplist.contains(userId)){
            //如果是点赞操作,点赞数 +1,用户id加进去
            comment.setThumbupnum(comment.getThumbupnum() +1);
            thumbuplist.add(userId);
        }else {
            //如果是非点赞操作,点赞数 -1,用户id移除出去
            comment.setThumbupnum(comment.getThumbupnum() -1);
            thumbuplist.remove(userId);
        }

        //update
        repository.save(comment);
    }
}
